//
//  ZHomeModelViewModel.swift
//  swift-weibo
//
//  Created by zero on 17/3/24.
//  Copyright © 2017年 zero. All rights reserved.
//

import UIKit
import SDWebImage

class ZHomeModelViewModel: NSObject {

    
    
//    /// 用户头像地址（中图），50×50像素
//    var profile_image_url: String?
//    /// 认证类型 -1：没有认证，1，认证用户，2,3,5: 企业认证，220: 达人
//    var verified: Int = 0
//    /// 会员等级 1-6
//    var mbrank: Int = 0

    var imgMbrank : UIImage?
    var imgVerified : UIImage?
    var profile_image_url :URL?
    
    var timeString:String?{
        
        
        return getTimeString(created_at: homeModel?.created_at)
    }
    
    var sourceString: String?
    
    //  内容处理
    var originalContentString:NSMutableAttributedString?
    var retweetContentString:NSMutableAttributedString?
    
    var homeModel:ZHomeModel?{
        
        didSet{
            
            profile_image_url = URL(string: (homeModel?.user?.profile_image_url)!)
            imgMbrank = getMbrank(mbrank: homeModel?.user?.mbrank ?? 0 )
            imgVerified = getVerified(verified: homeModel?.user?.verified ?? 0)
            
            sourceString = getSourceString(source: homeModel?.source)
            
            originalContentString = getEmojiText(contentText: homeModel?.text)
            retweetContentString = getEmojiText(contentText: homeModel?.retweeted_status?.text)
        }
    }
    
    
    
}

extension ZHomeModelViewModel{
    
    func getEmojiText(contentText:String?) -> NSMutableAttributedString?{
        
        guard let targetString = contentText  else {
            
            print("ZHomeModelViewModel字符串为空")
            return nil
        }
        
        let mutableRes = try! NSRegularExpression(pattern: "\\[[\\w]+\\]", options: []).matches(in: targetString, options: [], range: NSRange(location: 0, length: targetString.characters.count))
        
        //  创建可变的富文本
        let attMutableString = NSMutableAttributedString(string: targetString)
        
        //  遍历结果集
        for res in mutableRes.reversed(){
            
            let str = (targetString as NSString).substring(with: res.range)
            
            guard let emojiModel = ZBundleTools.share.getModelFromString(res: str) else {
                
                return nil
                
            }
            
            let imagePath = emojiModel.allPath ?? ""
            
            guard let image = UIImage(named: imagePath, in: ZBundleTools.share.getPath(), compatibleWith: nil) else {
                
                continue
            }
            
            //  创建不可变的富文本
            let attrString = NSMutableAttributedString.yy_attachmentString(withEmojiImage: image, fontSize: 14)
            
            //  替换
            attMutableString.replaceCharacters(in: res.range, with: attrString!)
            
        }
        
        //匹配用户：@[a-zA-Z0-9\\u4e00-\\u9fa5_\\-]+

        setHightLightText(content: attMutableString, pattern: "@[a-zA-Z0-9\\u4e00-\\u9fa5_\\-]+")
//        //匹配话题：#[^#]+#

        setHightLightText(content: attMutableString, pattern: "#[^#]+#")
//        //匹配URL：([hH]ttp[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\-~!@#$%^&*+?:_/=<>.',;]*)?
        setHightLightText(content: attMutableString, pattern: "([hH]ttp[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\-~!@#$%^&*+?:_/=<>.',;]*)?")


        return attMutableString
        
    }
    
    fileprivate func setHightLightText(content:NSMutableAttributedString,pattern:String){
        
        //
        let mutableRes = try! NSRegularExpression(pattern: pattern, options: []).matches(in: content.string, options: [], range: NSRange(location: 0, length: content.string.characters.count))
        
//        YYTextBorder *border = [YYTextBorder borderWithFillColor:[UIColor grayColor] cornerRadius:3];
//        
//        YYTextHighlight *highlight = [YYTextHighlight new];
//        [highlight setColor:[UIColor whiteColor]];
//        [highlight setBackgroundBorder:highlightBorder];
//        highlight.tapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
//            NSLog(@"tap text range:...");
//            // 你也可以把事件回调放到 YYLabel 和 YYTextView 来处理。
//        };
//        
//        // 2. 把"高亮"属性设置到某个文本范围
//        [attributedText yy_setTextHighlight:highlight range:highlightRange];
        
        let border = YYTextBorder.init(fill: UIColor.gray, cornerRadius: 2)
        let highlight = YYTextHighlight()
        
        highlight.setColor(UIColor.white)
        highlight.setBackgroundBorder(border)
        
        for res in mutableRes{
            
            content.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: res.range)
            
            content.yy_setTextHighlight(highlight, range: res.range)
        }
        
    }
}

extension ZHomeModelViewModel{
    
    //  来源的处理
    fileprivate func getSourceString(source:String?) ->String?{
        
        guard let sou = source,sou.contains("\">") else{
            
            return "来自远方的朋友"
        }
        // startIndex        endIndex
        // low -> up        low -> up
        //  \>     content   </
        let startIndex = sou.range(of: "\">")!
        let endIndex = sou.range(of: "</")!
        
        let souString = sou.substring(with: startIndex.upperBound ..< endIndex.lowerBound)
        
        return souString
    }
    
    //  时间的处理
    fileprivate func getTimeString(created_at:Date?) ->String?{
        
        guard let sinceDate = created_at else {
            
            return "遥远的未来"
        }
        
        let fommter = DateFormatter()
        
        //  是否是今年
        let isThis = self.isThisYear(created_at: sinceDate)
        
        //  是今年
        if isThis {
            
            //  日历类对象
            let calender = Calendar.current
            //  是不是今天
            
            if calender.isDateInToday(sinceDate) {
                
                //  获取秒数
                let second = Int(Date().timeIntervalSince(sinceDate))
                
                if second < 60 {
                    
                    return "刚刚"
                }else if second < 60 * 60{
                    
                    return "\(second/60)分钟前"
                }else{
                    fommter.dateFormat = "\(second/3600)小时前"
                }
                
            }else if calender.isDateInYesterday(sinceDate){
                
                fommter.dateFormat = "昨天 hh时mm分"
            }else{
                
                fommter.dateFormat = "MM月dd日 hh时mm分"
            }
            
        }else{
            
            //  不是今年
            fommter.dateFormat = "yyyy年MM月dd日 hh时mm分"
            
        }
        
        let timeString = fommter.string(from: sinceDate)
        
        return timeString
    }
    
    fileprivate func isThisYear(created_at:Date) -> Bool{
        
        //  格式化工具
        
        let fomtter = DateFormatter()
        
        fomtter.dateFormat = "yyyy"
        
        let createdTime = fomtter.string(from: created_at)
        
        //  获取当前年份
        let sinceYear = fomtter.string(from: Date())
        
        
        return createdTime == sinceYear
    }
    
    //  认证
    fileprivate func getVerified(verified : Int) -> UIImage{
        
        switch verified {
        case 1:
            
            return UIImage(named: "avatar_vip")!
            
        case 2,3,5:
            
            return UIImage(named: "avatar_enterprise_vip")!
            
        case 220:
            
            return UIImage(named: "avatar_grassroot")!
            
        default:
            return UIImage(named: "avatar_vgirl")!
        }
        
    }
    
    //  会员
 
    fileprivate func getMbrank(mbrank:Int) -> UIImage{
        
        if mbrank == 0 {
            
            return UIImage(named: "common_icon_membership_expired")!
        }
        
        return UIImage(named: "common_icon_membership_level\(mbrank)")!
    }
}
